package controller;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.opensymphony.xwork2.ActionSupport;

import dao.UpdateNewPassVisitorDAO;

public class EmailerResetPasswordAction extends ActionSupport {
    private final String from = "developerteam44@gmail.com";
    private final String password = "qttt12345";
    private String to;

    static Properties properties = new Properties();
    static
    {
       properties.put("mail.smtp.host", "smtp.gmail.com");
       properties.put("mail.smtp.socketFactory.port", "465");
       properties.put("mail.smtp.socketFactory.class",
                      "javax.net.ssl.SSLSocketFactory");
       properties.put("mail.smtp.auth", "true");
       properties.put("mail.smtp.port", "465");
    }

    public String execute() 
    {
       String result = SUCCESS;
       try
       {
    	  String newPass = GenRamdomPassword.genPassword();
    	  if (!UpdateNewPassVisitorDAO.isResetPassword(to, EncyptPassword.encryptMD5(newPass))) {
    		  throw new Exception(" Email not exist !");
    	  }
          Session session = Session.getDefaultInstance(properties,  
             new javax.mail.Authenticator() {
             protected PasswordAuthentication 
             getPasswordAuthentication() {
             return new 
             PasswordAuthentication(from, password);
             }});

          Message message = new MimeMessage(session);
          message.setFrom(new InternetAddress(from));
          message.setRecipients(Message.RecipientType.TO, 
          InternetAddress.parse(to));
          message.setSubject("Reset Password");
          message.setText(" Your's password is: " + newPass);
          Transport.send(message);
       }
       
       catch(Exception ex) {
     	 result = ERROR;
         System.out.println(" Mailer says error:  " + ex.getMessage());
       }
       return result;
    }

	public String getTo() {
		return to;
	}

	public void setTo(String to) {
		this.to = to;
	}

	public static Properties getProperties() {
		return properties;
	}

	public static void setProperties(Properties properties) {
		EmailerResetPasswordAction.properties = properties;
	}	   	  
}
